package com.feihong.yw189.activity.yonghuzhongxin.zhuanzhang;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.yonghuzhongxin.AddmoeyDialog;
import com.feihong.yw189.adapter.MyBaseAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.http.HttpTools;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.User.MessageItem;
import com.feihong.yw189.model.User.money.RollOutDetailModel;
import com.feihong.yw189.model.User.money.RollOutModel;
import com.holenzhou.pullrecyclerview.BaseRecyclerAdapter;
import com.holenzhou.pullrecyclerview.PullRecyclerView;
import com.holenzhou.pullrecyclerview.layoutmanager.XLinearLayoutManager;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 转出记录
 */
public class RollOutActivity extends BaseActivity {
    @BindView(R.id.rl_goback)
    RelativeLayout ivBack;
    @BindView(R.id.txt_pagetitle)
    TextView txtPagetitle;
    @BindView(R.id.iv_lin)
    ImageView ivLin;
    @BindView(R.id.iv_confirm)
    TextView ivConfirm;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.pull_recycler_view)
    PullRecyclerView mPullRecyclerView;

    private MyBaseAdapter mAdapter;
    private int pageGlobal = 2;
    private Unbinder unbinder;

    AddmoeyDialog dialog = null;

    @BindView(R.id.null_data_layout)
    RelativeLayout mNullDataLayout;
    @BindView(R.id.connect_net_error_layout)
    LinearLayout mErrorLayout;
    @BindView(R.id.null_data_layout_txt)
    TextView mNullDataLayoutWarningTv;
    private int mDataSize = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_money_detail);
        unbinder = ButterKnife.bind(this);

        initView();
        bindData();
    }

    @Override
    public void setTheme() {

    }

    private void initView() {
        setBackButtonFinish();
        setPageTitle("转出记录");
        ivLin.setVisibility(View.GONE);
    }

    private void noDataLayout() {
        if (mNullDataLayout.getVisibility() == View.GONE) {
            mErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.VISIBLE);
        }
    }

    private void netErrorLayout() {
        if (mErrorLayout.getVisibility() == View.GONE) {
            mErrorLayout.setVisibility(View.VISIBLE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.requery_data_tv})
    void onClick() {
        normalDataLayout();
        mPullRecyclerView.autoRefresh();
    }

    private void normalDataLayout() {
        if (mErrorLayout.getVisibility() == View.VISIBLE || mNullDataLayout.getVisibility() == View.VISIBLE) {
            mErrorLayout.setVisibility(View.GONE);
            mNullDataLayout.setVisibility(View.GONE);
            mPullRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    private void bindData() {
        Map<String, Object> map = new HashMap();
        map.put("title", R.id.my_adding_money_title);
        map.put("time", R.id.my_adding_money_time);
        map.put("message", R.id.my_adding_money_message);
        map.put("subTitle", R.id.my_adding_money_subtitle);
        map.put("imageResId", R.id.my_adding_money_img);
//        map.put("imgUrl", R.id.sys_mess_img);

        // 初始化PullRecyclerView
        mPullRecyclerView.setLayoutManager(new XLinearLayoutManager(this));
        mAdapter = new MyBaseAdapter(this, R.layout.my_adding_money_item, map, 4);
        mPullRecyclerView.setAdapter(mAdapter);

        mPullRecyclerView.setColorSchemeResources(R.color.appBlue); // 设置下拉刷新的旋转圆圈的颜色
        mPullRecyclerView.enablePullRefresh(true); // 开启下拉刷新，默认即为true，可不用设置


        //刷新监听
        mPullRecyclerView.setOnRecyclerRefreshListener(new PullRecyclerView.OnRecyclerRefreshListener() {
            @Override
            public void onPullRefresh() {
                // 下拉刷新网络请求
                mPullRecyclerView.enableLoadDoneTip(false, R.string.load_done_tip); // 开启数据全部加载完成时的底部提示，默认为false
                mPullRecyclerView.enableLoadMore(false);
                Callback.Cancelable drawCallBack = App.getApp().getHttpTools().addingMoneyList(1, 10, HttpTools.MY_MONEY_OUT, CallBackDown);
                RequestTools.addNewRequest(RollOutActivity.class.getName(), drawCallBack);

            }

            @Override
            public void onLoadMore() {
                mPullRecyclerView.enableLoadDoneTip(true, R.string.load_done_tip); // 开启数据全部加载完成时的底部提示，默认为false
                Callback.Cancelable downCallBack = App.getApp().getHttpTools().addingMoneyList(pageGlobal, 10, HttpTools.MY_MONEY_OUT, callBackUp);
                RequestTools.addNewRequest(RollOutActivity.class.getName(), downCallBack);
            }
        });
        mPullRecyclerView.postRefreshing();

        mAdapter.setOnItemClickListener(messageItem -> {
            if (isFastDoubleClick(OtherlastClickTime)) {
                return;
            }
            OtherlastClickTime = System.currentTimeMillis();
            if (dialog != null) {
                dialog.cancel();
            }
            Callback.Cancelable clickCallBack = App.getApp().getHttpTools().addingMoneyDetail(messageItem.getId(), HttpTools.MY_MONEY_OUT_DETAIL, 2, callBackClick);
            RequestTools.addNewRequest(RollOutActivity.class.getName(), clickCallBack);
        });
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    //下拉获取信息
    RequestCallBack<String> CallBackDown = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                RollOutModel addMoneyModel = JSON.parseObject(result, RollOutModel.class);
                if (addMoneyModel != null) {
                    //有数据
                    mDataSize = 0;
                    if (addMoneyModel.getStatus() == 1) {
                        List<RollOutModel.DataBean.ListBean> dataAccountList = addMoneyModel.getData().getList();

                        //清除原数据,加载新数据,上拉加载
                        if (dataAccountList != null && dataAccountList.size() > 0) {
                            MessageItem model;
                            //重置
                            pageGlobal = 2;
                            List<MessageItem> mData = new ArrayList<>();
                            for (RollOutModel.DataBean.ListBean message : dataAccountList) {
                                model = new MessageItem();
                                model.setTitle(message.getOpen_bank() + "(" + message.getBank_num() + ")");
                                model.setSubTitle(message.getMoney());
                                model.setTime(message.getLast_time());
                                model.setMessage(message.getIs_ok_name());
                                model.setOrder_sn(message.getTrade_id());
                                model.setId(message.getId());
                                model.setImageResId(mipmapId(message.getOpen_bank()));
                                mData.add(model);
                            }
                            mAdapter.clear();
                            mAdapter.addAll(mData);
                            //开启上拉加载更多
                            mDataSize += dataAccountList.size();
                            if (dataAccountList.size() >= 10) {
                                mPullRecyclerView.enableLoadMore(true);
                            }
                            normalDataLayout();
                        } else {
                            //数据为空,显示空页面
                            noDataLayout();
                        }
                    } else {
                        //为空显示空页面
                        noDataLayout();
                    }
                } else {
                    noDataLayout();
                }
            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            if (mDataSize == 0) {
                netErrorLayout();
            } else {
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {
        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopRefresh();
        }
    };

    //上拉更新信息
    RequestCallBack<String> callBackUp = new RequestCallBack<String>() {

        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                //json解析
                RollOutModel addMoneyModel = JSON.parseObject(result, RollOutModel.class);
                if (addMoneyModel != null) {
                    //有数据
                    if (addMoneyModel.getStatus() == 1) {
                        pageGlobal++;
                        List<RollOutModel.DataBean.ListBean> dataList = addMoneyModel.getData().getList();
                        int pageSize = dataList.size();
                        if (pageSize > 0) {
                            if (pageSize < 10) {
                                mPullRecyclerView.enableLoadMore(false);
                            }
                            MessageItem model;
                            List<MessageItem> mDatas = new ArrayList<>();
                            for (RollOutModel.DataBean.ListBean message : dataList) {
                                model = new MessageItem();
                                model.setTitle(message.getOpen_bank() + "(" + message.getBank_num() + ")");
                                model.setSubTitle(message.getMoney());
                                model.setTime(message.getLast_time());
                                model.setMessage(message.getIs_ok_name());
                                model.setOrder_sn(message.getTrade_id());
                                model.setId(message.getId());
                                model.setImageResId(mipmapId(message.getOpen_bank()));
                                mDatas.add(model);
                            }
                            mAdapter.addAll(mDatas);
                            mDataSize += pageSize;
                            //结束的时候打开上拉
                        } else {
                            //数据为空,没数据了,关闭上拉
                            mPullRecyclerView.enableLoadMore(false);
                        }
                    } else {
                        mPullRecyclerView.enableLoadMore(false);
                    }
                } else {
                    showErrorToast("解析出错,请重试");
                }

            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            showToast(getResources().getString(R.string.connect_sever_error_toast));
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {
            if (activityIsDestory()) {
                return;
            }
            mPullRecyclerView.stopLoadMore();
        }
    };

    //点击回调
    RequestCallBack<String> callBackClick = new RequestCallBack<String>() {
        @Override
        public void onSuccess(String result) {
            if (activityIsDestory()) {
                return;
            }
            try {
                RollOutDetailModel model = JSON.parseObject(result, RollOutDetailModel.class);
                if (model != null) {
                    //请求成功！
                    if (model.getStatus() == 1) {
                        RollOutDetailModel.DataBean.ListBean detailMessage = model.getData().getList();
                        dialog = new AddmoeyDialog(RollOutActivity.this, detailMessage);
                        dialog.setCancelable(true);
                        dialog.setCanceledOnTouchOutside(true);// 屏蔽点击空拍dialog消失
                        dialog.showDialog();
                    } else {
                        showErrorToast(model.getInfo());
                    }
                } else {
                    showErrorToast("解析出错,请重试");
                }
            } catch (Exception ex) {
            }
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            if (activityIsDestory()) {
                return;
            }
            showToast(getResources().getString(R.string.connect_sever_error_toast));
        }

        @Override
        public void onCancelled(Callback.CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 清空请求
        RequestTools.removeRequest(RollOutActivity.class.getName());

        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    //加入图标判断
    private int mipmapId(String message) {
        if (message.contains("行")) {
            return R.mipmap.my_adding_transfer;
        } else if (message.contains("支付宝")) {
            return R.mipmap.my_adding_alipay;
        }
        return R.mipmap.pay_turn;
    }

    private static long OtherlastClickTime;

    private static boolean isFastDoubleClick(long lastClickTime) {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 1000 * 2) {
            return true;
        }
        return false;
    }

}